<template>
  <div class="container">
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="title" label="广告标题">
        <el-input v-model="form.title" placeholder="广告标题"></el-input>
      </el-form-item>
      <el-form-item prop="category" label="选择位置">
        <el-select v-model="form.category" placeholder="选择位置">
          <el-option v-for="(item,index) in options.ad_category" :key="index" :label="item.name" :value="item.val">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="type" label="类型">
        <el-select v-model="form.type" placeholder="图片">
          <el-option v-for="(item,index) in options.ad_type" :key="index" :label="item.name" :value="item.val">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="orderNo" label="显示顺序">
        <el-input v-model.number="form.orderNo" placeholder="显示顺序"></el-input>
      </el-form-item>
      <el-form-item prop="startTime" label="开始时间">
        <el-date-picker v-model="form.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"></el-date-picker>
      </el-form-item>
      <el-form-item prop="endTime" label="结束时间">
        <el-date-picker v-model="form.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间">
        </el-date-picker>
        <el-checkbox v-model="form.unlimitTime">不限时间</el-checkbox>
      </el-form-item>

      <el-form-item prop="remark" label="备注">
        <el-input type="textarea" v-model="form.remark" rows="6" placeholder="备注"></el-input>
      </el-form-item>

      <el-form-item prop="imgPath" label="图片上传" v-if="form.type===1">
        <div class="upload">
          <el-upload ref="upload" class="upload-demo" action :limit="1" :http-request="postPic" :show-file-list="false"
            list-type="picture" v-if="!form.imgPath">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <ul v-else>
            <li @click="handleRemove">
              <img :src="form.imgPath" alt />
            </li>
          </ul>
        </div>
        <!-- <el-upload
                    class="avatar-uploader"
                    action
                    :class="{disabled:uploadDisabled}"
                    :http-request="postPic"
                    :limit="1"
                    :on-remove="handleRemove"
                    list-type="picture-card"
                >
                    <img v-if="form.imgPath" :src="form.imgPath" class="avatar" />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>-->
      </el-form-item>
      <el-form-item prop="url" label="跳转链接">
        <el-input v-model="form.url" placeholder="跳转链接"></el-input>
      </el-form-item>
      <el-form-item class="btn_box">
        <el-button class="finish_btn" type="primary" @click="onSubmit" :loading="loading"
          v-loading.fullscreen.lock="loading">保存修改</el-button>
        <el-button class="finish_btn" type="primary" @click="toADList">取消返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { postPicture } from '../../../api/index';
import { AddAdvertisement, ADInfo, ADUpdate, getADtype, getADPosition } from '../../../api/content';
export default {
  name: '',
  data () {
    var validateEndTime = (rule, value, callback) => {
      if (!this.form.unlimitTime && !value) {
        callback(new Error('请选择结束时间！'));
      } else {
        callback();
      }
    };
    var validateOrderNo = (rule, value, callback) => {
      console.log(value);

      if (value > 500) {
        callback(new Error('显示顺序不能超过500'));
      } else if (typeof value !== 'number') {
        callback(new Error('显示顺序为数字'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      form: {
        title: '',
        category: '',
        type: '',
        orderNo: null,
        startTime: '',
        endTime: '',
        remark: '',
        imgPath: '',
        url: '',
        unlimitTime: ''
      },
      options: {
        ad_type: [],
        ad_category: []
      },
      rules: {
        title: [
          { required: true, message: '请输入广告标题', trigger: 'blur' },
          { max: 50, message: '广告标题不能超过20个字' }
        ],
        category: [{ required: true, message: '请选择广告位置', trigger: 'change' }],
        type: [{ required: true, message: '请选择广告类型', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        orderNo: [
          { required: true, message: '请输入显示顺序', trigger: 'blur' },
          { validator: validateOrderNo }],
        endTime: [{ validator: validateEndTime, trigger: 'change' }],
        remark: [
          { max: 500, message: '备注不能超过500个字' }
        ],
        imgPath: [{ required: true, message: '请上传图片', trigger: 'change' }]
      }
    };
  },
  created () {
    let obj = {
      ad_type: getADtype,
      ad_category: getADPosition
    };
    Promise.all(Object.values(obj).map(item => item())).then(data => {
      Object.keys(obj).forEach((key, index) => {
        this.options[key] = data[index].data;
      });
      console.log(this.options);
      this.getADInfo();
    });
    // let code = ['ad_type', 'ad_category'];
    // console.log(this.$route.query);
    // new Promise((resolve, reject) => {
    //     code.forEach(item => {
    //         findDictByCode(item).then(data => {
    //             this.options[item] = data.data;
    //             if (item === 'ad_category') {
    //                 resolve();
    //             }
    //         });
    //     });
    // }).then(() => {
    //     if (this.$route.query.id) {
    //         this.form.id = this.$route.query.id;
    //         ADInfo({id:this.form.id}).then(data => {
    //             console.log(data);
    //             Object.keys(this.form).forEach(item => {
    //                 this.form[item] = data.data[item];
    //             });
    //         });
    //     }
    // });
  },
  computed: {
    uploadDisabled () {
      console.log(this.form.imgPath);
      return this.form.imgPath;
    }
  },
  methods: {
    handleRemove () {
      this.form.imgPath = '';
    },
    toADList () {
      this.$router.push({ path: '/advertisement' });
    },
    getDic () { },
    getADInfo () {
      if (this.$route.query.id) {
        this.form.id = this.$route.query.id;
        let formData = new FormData();
        formData.append('id', this.form.id)
        ADInfo(formData).then(data => {
          console.log(data);
          Object.keys(this.form).forEach(item => {
            if (item === 'orderNo') {
              this.form[item] = parseInt(data.data[item]);
            } else {
              this.form[item] = data.data[item];
            }
            console.log(this.form);
          });
        });
      }
    },
    postPic (param) {
      let fd = new FormData();
      fd.append('file', param.file);
      postPicture(fd).then(data => {
        if (data.success) {
          this.form.imgPath = data.data.fileUrl;
          console.log(data);
        } else {
          this.$message.error(`${data.msg}`);
        }
      });
    },
    handleRemove () {
      this.form.imgPath = '';
    },
    onSubmit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true;
          (this.form.id ? ADUpdate(this.form) : AddAdvertisement(this.form)).then(data => {
            console.log(data);
            if (data.success) {
              this.loading = false;
              this.$message.success(this.form.id ? '修改成功' : '添加成功');
              this.$router.push('/Advertisement');
            } else {
              this.loading = false;
              this.$message.error(`${data.msg}`);
            }
          });
        }
      });
    }
  }
};
</script>

<style scoped>
.container /deep/ .el-form-item__label {
    width: 120px;
}
.el-form .el-form-item /deep/ .el-form-item__error {
    left: 120px;
}
.el-input {
    width: 300px;
    margin-right: 10px;
}
.el-textarea {
    width: 300px;
}
.el-select {
    width: 300px;
}
.btn_box {
    padding-left: 118px;
}
.btn_box .el-button {
    width: 100px;
    margin-right: 80px;
}
.upload /deep/ .el-upload {
    display: flex;
    align-items: center;
    width: 94px;
    height: 24px;
    line-height: 32px;
}
.upload /deep/ .upload-demo {
    display: inline-block;
    width: 94px;
    height: 24px;
    line-height: 24px;
    background: rgba(24, 147, 252, 1);
    opacity: 1;
}
.upload /deep/ .el-button {
    width: 94px;
    height: 24px;
    line-height: 0px;
    background: rgba(24, 147, 252, 1);
    opacity: 1;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -ms-box-sizing: border-box;
    -o-box-sizing: border-box;
}
.upload ul {
    display: inline-block;
    list-style: none;
    width: 500px;
    overflow: hidden;
}
.upload ul li {
    float: left;
    width: 124px;
    height: 124px;
    margin-right: 40px;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(24, 147, 252, 1);
    opacity: 1;
    margin-bottom: 24px;
}
.upload ul li img {
    width: 100%;
    height: 100%;
}
</style>